package com.etc.week9_day04_nacosconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class NacosController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    private String appName = "nacos-provider";

    @GetMapping("/echo/app-name")
    public String echoAppName() {
        //使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");
        String url = String.format("http://%s:%s/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
//       String url = "http://172.16.2.20:8081/echo/nacos-provider";
        System.out.println("request url:" + url);
        return restTemplate.getForObject(url, String.class);
    }


    @GetMapping("/echo/app-name2")
    public String echoAppName2() {
        String url = "http://172.16.2.20:8001/echo/hello";
        System.out.println("request url:" + url);
        return restTemplate.getForObject(url, String.class);
    }

}